import pygame

from sprites import TileCursor, GroundTile

from constants import *

class CameraGroup(pygame.sprite.Group):
    def __init__(self, tile_cursor: TileCursor):
        super().__init__()
        self.offset = pygame.math.Vector2()
        self.tile_sprites = []
        self.tile_cursor = tile_cursor

    def camera_draw(self, surface, player):
        self.center_target_camera(player)
        mouse_pos = pygame.mouse.get_pos()
        update_tile_cursor = False
        for sprite in self.tile_sprites:
            offset_pos = sprite.rect.topleft - self.offset
            surface.blit(sprite.image, offset_pos)
            cursor_check_rect = pygame.rect.Rect(sprite.rect)
            if cursor_check_rect.collidepoint(mouse_pos[0] + self.offset[0], mouse_pos[1] + self.offset[1]):
                self.tile_cursor.rect.topleft = cursor_check_rect.topleft
                update_tile_cursor = True
        for sprite in sorted(self.sprites(), key=lambda sprite: sprite.rect.centery):
            offset_pos = sprite.rect.topleft - self.offset
            surface.blit(sprite.image, offset_pos)
        if update_tile_cursor:
            offset_pos = self.tile_cursor.rect.topleft - self.offset
            surface.blit(self.tile_cursor.image, offset_pos)

    def center_target_camera(self, target):
        self.offset.x = target.rect.centerx - (SCREEN_WIDTH // 2)
        self.offset.y = target.rect.centery - (SCREEN_HEIGHT // 2)

    def add_tile(self, sprite: GroundTile):
        self.tile_sprites.append(sprite)

    def get_sprite_coordinate_under_cursor(self) -> tuple[int,int]:
        mouse_pos = pygame.mouse.get_pos()
        return int((mouse_pos[0] + self.offset[0]) // 64), \
               int((mouse_pos[1] + self.offset[1]) // 64)
